import {ApiConfigItem, GlobalHeadersConfig, ProxyConfigItem, HeaderValue} from '../types/config';

export interface InterceptorConfig {
    apiConfig: ApiConfigItem[];
    globalHeaders: GlobalHeadersConfig;
    proxyConfigs: ProxyConfigItem[];
}

export interface RequestInterceptor {
    init(): void;
    destroy(): void;
}

export abstract class BaseInterceptor implements RequestInterceptor {
    protected config: InterceptorConfig;

    constructor(config: InterceptorConfig) {
        this.config = config;
    }

    protected handleProxy(url: string, isRedirected: boolean): string {
        const enabledProxies = this.config.proxyConfigs.filter(config => config.enabled);

        // 检查是否有启用的全局代理
        const globalProxy = enabledProxies.find(config => config.type === 'global');
        if (globalProxy) {
            console.log("使用全局代理");
            return globalProxy.url.replace('{target}', encodeURIComponent(url));
        }

        // 检查是否有匹配的接口代理
        const interfaceProxy = enabledProxies.find(config =>
            config.type === 'interface' && isRedirected
        );
        if (interfaceProxy) {
            console.log("使用接口代理");
            return interfaceProxy.url.replace('{target}', encodeURIComponent(url));
        }

        return url;
    }

    protected getEnabledHeaders(headers: Record<string, HeaderValue> = {}): Record<string, string> {
        return Object.entries(headers)
            .filter(([_, value]) => value.enabled)
            .reduce((acc, [key, value]) => ({
                ...acc,
                [key]: value.value
            }), {} as Record<string, string>);
    }

    protected processUrl(url: string): {
        finalUrl: string;
        matchedConfig: ApiConfigItem | null;
        isRedirected: boolean
    } {
        let matchedConfig: ApiConfigItem | null = null;
        let isRedirected = false;
        let finalUrl = url;

        // 只处理启用的配置
        const enabledConfigs = this.config.apiConfig.filter(c => c.enabled);
        for (const config of enabledConfigs) {
            const {target, replacement} = config;
            const targetWithoutProtocol = target.replace(/^https?:\/\//, '');
            const urlWithoutProtocol = finalUrl.replace(/^https?:\/\//, '');

            if (urlWithoutProtocol.includes(targetWithoutProtocol)) {
                // 保持原始协议或使用替换URL的协议
                const originalProtocol = finalUrl.match(/^(https?):\/\//)?.[1] || 'http';
                const replacementProtocol = replacement.match(/^(https?):\/\//)?.[1];

                // 如果替换URL指定了协议，使用其协议；否则保持原协议
                const newProtocol = replacementProtocol || originalProtocol;

                // 构建新的URL
                const newUrl = replacement.replace(/^https?:\/\//, '');
                finalUrl = finalUrl.replace(targetWithoutProtocol, newUrl);
                finalUrl = finalUrl.replace(/^https?:\/\//, `${newProtocol}://`);

                matchedConfig = config;
                console.log('✅ 重定向:', {
                    从: target,
                    到: replacement,
                    最终URL: finalUrl
                });
                isRedirected = true;
                break;
            }
        }

        // 处理 URL 参数
        if (matchedConfig?.params) {
            const urlObj = new URL(finalUrl);
            Object.entries(matchedConfig.params).forEach(([key, value]) => {
                urlObj.searchParams.set(key, String(value));
            });
            finalUrl = urlObj.toString();
            console.log('🔄 添加URL参数后:', finalUrl);
        }

        return {finalUrl, matchedConfig, isRedirected};
    }

    protected processRequestBody(originalBody: any, matchedConfig: ApiConfigItem | null): any {
        if (!matchedConfig?.body || !originalBody) {
            return originalBody;
        }

        console.log('🔍 发现请求体配置，正在修改请求体');
        let mergedBody;

        try {
            if (originalBody instanceof FormData) {
                // 处理 FormData 类型
                const newFormData = new FormData();
                // 保留原有的 FormData 数据
                for (let pair of originalBody.entries()) {
                    newFormData.append(pair[0], pair[1]);
                }
                // 添加配置中的数据
                const configBody = typeof matchedConfig.body === 'string'
                    ? JSON.parse(matchedConfig.body)
                    : matchedConfig.body;
                Object.entries(configBody).forEach(([key, value]) => {
                    newFormData.append(key, String(value));
                });
                mergedBody = newFormData;
            } else {
                // 处理请求体
                if (typeof originalBody === 'string' && !originalBody.trim().startsWith('{')) {
                    // 如果原始请求体不是 JSON 格式，直接使用配置的请求体
                    console.log('原始请求体不是 JSON 格式，将直接使用配置的请求体');
                    mergedBody = typeof matchedConfig.body === 'string'
                        ? matchedConfig.body
                        : JSON.stringify(matchedConfig.body);
                } else {
                    // 处理 JSON 类型
                    let originalJson = {};
                    if (originalBody) {
                        try {
                            originalJson = typeof originalBody === 'string'
                                ? JSON.parse(originalBody)
                                : originalBody;
                        } catch (e) {
                            console.log('原始请求体解析失败，将使用空对象');
                        }
                    }

                    let configJson = {};
                    try {
                        configJson = typeof matchedConfig.body === 'string'
                            ? JSON.parse(matchedConfig.body)
                            : matchedConfig.body;
                    } catch (e) {
                        console.error('配置的请求体不是有效的 JSON 格式');
                        return originalBody;
                    }

                    mergedBody = JSON.stringify({
                        ...originalJson,
                        ...configJson
                    });
                }
            }

            console.log('🔄 修改后的请求体:', mergedBody instanceof FormData ? '包含FormData数据' : mergedBody);
            return mergedBody;
        } catch (error) {
            console.error('❌ 处理请求体时出错:', error);
            return originalBody;
        }
    }

    abstract init(): void;
    abstract destroy(): void;
} 